package com.yyk.yiliao.ui.activity.dingdan.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.listener.DialogSureCancelListenter;
import com.yyk.yiliao.ui.activity.detail.activity.PayPleaceOrder_Activity;
import com.yyk.yiliao.ui.activity.shopcart.ShopCart_Activity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.TimerUtil;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.CartOrderdel_Info;
import com.yyk.yiliao.bean.CartStatuskey_Info;
import com.yyk.yiliao.bean.OderBuy_Info;
import com.yyk.yiliao.bean.OderOrderPay_Info;
import com.yyk.yiliao.bean.OrderOrderRestart_Info;
import com.yyk.yiliao.widget.diver.CustomDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 商品订单 全部跳转到这个类
 */
public class DingdanXiangqing4_Activity extends BaseActivity {

    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_stname)
    TextView tvStname;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.tv_total2)
    TextView tvTotal2;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_createTime)
    TextView tvCreatetime;

    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.rl_1)
    RelativeLayout rl1;
    @BindView(R.id.rl_3)
    RelativeLayout rl3;
    @BindView(R.id.rl_5)
    RelativeLayout rl5;
    @BindView(R.id.rl_4)
    RelativeLayout rl4;
    @BindView(R.id.rl_2)
    RelativeLayout rl2;
    @BindView(R.id.rl_6)
    RelativeLayout rl6;
    @BindView(R.id.tv_delete2)
    TextView tvDelete2;
    @BindView(R.id.tv_pinglun)
    TextView tvPinglun;
    @BindView(R.id.tv_confirm2)
    TextView tvConfirm2;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.ll_zk)
    LinearLayout llZk;
    private BaseRecyclerAdapter<OrderOrderRestart_Info.DataBean.GoodslistBean> adapter;
    private String number;
    private int postion;


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        handler.removeCallbacks(runnable);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_dingdan_xiangqing4;
    }

    @Override
    public void initView() {
        initToolbar();
    }

    private void initToolbar() {
        setBackArrow();
        setTitle("订单详情");
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageww(OrderOrderRestart_Info info) {
        Logger.e(info.toString()
                + "info");

        postion = info.getPostion();
        int status = info.getZkstatus();
        Logger.e(status + "ssssssssssss");
        if (status == 1) {
            rl1.setVisibility(View.VISIBLE);
            tvDelete2.setVisibility(View.VISIBLE);
            tvPay.setVisibility(View.VISIBLE);
            tvDelete.setVisibility(View.GONE);
            tvConfirm.setVisibility(View.GONE);
            tvConfirm2.setVisibility(View.GONE);
            int addtime = info.getAddtime(); //创建时间是固定的
            timer = TimerUtil.get(addtime);
            getTimeDuring(timer);
        } else if (status == 2) {
            rl2.setVisibility(View.VISIBLE);
            llZk.setVisibility(View.GONE);

        } else if (status == 3) {
            rl3.setVisibility(View.VISIBLE);

            llZk.setVisibility(View.GONE);
        } else if (status == 4) {
            rl4.setVisibility(View.VISIBLE);

            tvConfirm2.setVisibility(View.VISIBLE);
            tvDelete2.setVisibility(View.GONE);
            tvPay.setVisibility(View.GONE);
            tvDelete.setVisibility(View.GONE);
            tvConfirm.setVisibility(View.GONE);
        } else if (status == 5) {
            rl5.setVisibility(View.VISIBLE);

            tvDelete.setVisibility(View.VISIBLE);
            tvPinglun.setVisibility(View.VISIBLE);
            tvConfirm.setVisibility(View.VISIBLE);
            tvDelete2.setVisibility(View.GONE);
            tvConfirm2.setVisibility(View.GONE);
        } else if (status == 6) {
            rl6.setVisibility(View.VISIBLE);

            tvDelete.setVisibility(View.VISIBLE);
            tvConfirm.setVisibility(View.VISIBLE);
            tvDelete2.setVisibility(View.GONE);
            tvConfirm2.setVisibility(View.GONE);
            tvPay.setVisibility(View.GONE);
        }

        OrderOrderRestart_Info.AddressBean address = info.getAddress();
        if (address != null) {
            String dizhi = address.getAddress();
            tvAddress.setText(dizhi);
            tvName.setText(address.getName());
            tvPhone.setText(address.getPhone());
        }

        tvTotal.setText("¥" + info.getTotal());
        tvTotal2.setText("¥" + info.getTotal());

        String timer = TimerUtil.get(info.getAddtime());
        tvCreatetime.setText(timer);

        OrderOrderRestart_Info.DataBean dataBean = info.getData().get(0);
        tvStname.setText(dataBean.getSname());
        number = dataBean.getNumber(); //商品订单号
        tvNumber.setText(number);
        List<OrderOrderRestart_Info.DataBean.GoodslistBean> data = dataBean.getGoodslist();
        adapter = new BaseRecyclerAdapter<OrderOrderRestart_Info.DataBean.GoodslistBean>(DingdanXiangqing4_Activity.this, data, R.layout.zk) {
            @Override
            public void convert(BaseRecyclerHolder holder, final OrderOrderRestart_Info.DataBean.GoodslistBean goodslistBean, final int position, boolean isScrolling) {

                holder.setText(R.id.tv_num, "X" + goodslistBean.getNum());
                holder.setText(R.id.tv_money, "¥" + goodslistBean.getMoney());
                holder.setText(R.id.tv_sname, goodslistBean.getName());
                holder.setImageByUrl(R.id.iv_img, ApiService.BASE_URL + goodslistBean.getImg());

            }
        };
        rv.setLayoutManager(new LinearLayoutManager(DingdanXiangqing4_Activity.this));
        rv.addItemDecoration(new CustomDecoration(DingdanXiangqing4_Activity.this, CustomDecoration.VERTICAL_LIST, R.drawable.divider_f8_shopdingdan, 0));
        rv.setAdapter(adapter);
    }

    /**
     * https://blog.csdn.net/u010575303/article/details/54692567  支付倒计时
     */
    private String timer;
    @BindView(R.id.tv_addtime)
    TextView tvAddtime;//倒计时
    private long countdownTime;//倒计时的总时间(单位:毫秒)
    private String timefromServer;//从服务器获取的订单生成时间
    private long chaoshitime;//从服务器获取订单有效时长(单位:毫秒)

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            countdownTime -= 1000;//倒计时总时间减1
            SimpleDateFormat minforamt = new SimpleDateFormat("mm:ss");
            String hms = minforamt.format(countdownTime);//格式化倒计时的总时间
            if (countdownTime < 0) {
                tvAddtime.setText("00:00");
                DialogUtil.getIntanse().showReturnTips(mActivity, "", "订单时间超时", "确定", "", new DialogSureCancelListenter() {
                    @Override
                    public void onSureListenter() {
                        finish();
                    }

                    @Override
                    public void onCancelListenter() {

                    }
                }, true);
                handler.removeCallbacks(runnable);
                return;
            } else {
                tvAddtime.setText(hms);
            }
            handler.postDelayed(this, 1000);
        }
    };

    private void getTimeDuring(String timefromServer) {
        chaoshitime = 30 * 60 * 1000;//应该从服务器获取
        //        timefromServer = "2017-01-23 11:40:50";//应该从服务器获取
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date serverDate = df.parse(timefromServer);
            long duringTime = new Date().getTime() - serverDate.getTime();//计算当前时间和从服务器获取的订单生成时间的时间差
            countdownTime = chaoshitime - duringTime;//计算倒计时的总时间
            handler.postDelayed(runnable, 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    @OnClick({R.id.tv_delete, R.id.tv_confirm, R.id.tv_delete2, R.id.tv_confirm2, R.id.tv_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_delete:
                AlertDialog builder = DialogUtil.getIntanse().simpleDialog(this, null, "确定删除该订单吗？", "确定", "取消", new DialogUtil.AlertDialogListenter() {
                    @Override
                    public void queding() {
                        initDeleteDingdan(number);
                    }

                    @Override
                    public void quxiao() {
                        initGoumaiDingdan(number);
                    }
                });

                builder.show();
                break;
            case R.id.tv_delete2:
                AlertDialog tv_delete2 = DialogUtil.getIntanse().simpleDialog(DingdanXiangqing4_Activity.this, null, "确定取消该订单吗？", "确定", "取消", new DialogUtil.AlertDialogListenter() {
                    @Override
                    public void queding() {
                        initQuxiaoDingdan(number, 6);
                    }

                    @Override
                    public void quxiao() {

                    }
                });
                tv_delete2.show();
                break;
            case R.id.tv_confirm:
                initGoumaiDingdan(number);
                break;

            case R.id.tv_confirm2:
                AlertDialog tv_confirm2 = DialogUtil.getIntanse().simpleDialog(DingdanXiangqing4_Activity.this, null, "确定已收到货品？", "确定收货", "取消", new DialogUtil.AlertDialogListenter() {
                    @Override
                    public void queding() {
                        initQuerenDingdan(number, 5);
                    }

                    @Override
                    public void quxiao() {

                    }
                });

                tv_confirm2.show();
                break;
            case R.id.tv_pay:
                initPay(number);

                break;
        }
    }

    /**
     * 去支付
     */
    public void initPay(String number) {
        Map<String, String> map = new TreeMap<>();
        map.put("number", number);
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postOderOrderPay(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<OderOrderPay_Info>() {


                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(OderOrderPay_Info info) {
                        if (info.getCode() == 1) {
//                            Intent intent = new Intent(DingdanXiangqing4_Activity.this, PayPleaceOrder_Activity.class);
////                            EventBus.getDefault().postSticky(info);
//                            //2 是重新下单
//                            EventBus.getDefault().postSticky(new PayMessage(2, info.getAddtime(), info.getOrder_code(), info.getTotal(), info.getPay_type()));
//
//                            startActivity(intent);
                            Bundle bundle = new Bundle();
                            //1. 购物车结算
                            bundle.putString("endtype", "1");
//                            // 必须传一个值来判断调用银行卡第二次支付，验证码重新发送请求
//                            bundle.putBoolean("twosmsflag", true);
                            bundle.putString("out_trade_no", info.getOrder_code() + "");
                            bundle.putString("total", info.getTotal() + "");
                            bundle.putString("addtime", info.getAddtime() + "");
                            startAct(PayPleaceOrder_Activity.class, bundle);
                        }
                    }
                });
    }

    /**
     * 确认收货
     *
     * @param id
     * @param status
     */
    public void initQuerenDingdan(String id, int status) {
        Map<String, String> map = new TreeMap<>();

        map.put("id", id + "");
        map.put("status", status + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartStatuskey(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartStatuskey_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(CartStatuskey_Info info) {
                        if (info.getCode() == 1) {
                            finish();
                        }
                    }
                });
    }

    /**
     * 再次购买
     *
     * @param id
     */
    public void initGoumaiDingdan(String id) {
        Map<String, String> map = new TreeMap<>();
        map.put("number", id + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postOderBuy(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<OderBuy_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(OderBuy_Info info) {
                        if (info.getCode() == 1) {
                            Intent intent = new Intent(DingdanXiangqing4_Activity.this, ShopCart_Activity.class);
                            startActivity(intent);
//                            getActivity().finish();
                        } else {
                            ToastUtil.showShort(DingdanXiangqing4_Activity.this, "商品已失效");
                        }
                    }
                });
    }

    /**
     * 删除订单
     *
     * @param number
     */
    public void initDeleteDingdan(String number) {
        Map<String, String> map = new TreeMap<>();
        map.put("number", number);
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartOrderdel(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartOrderdel_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(CartOrderdel_Info info) {
                        if (info.getCode() == 1) {
                            finish();

                        } else {
                            ToastUtil.showShort(DingdanXiangqing4_Activity.this, info.getMsg());
                        }
                    }
                });
    }

    /**
     * 取消订单
     *
     * @param number
     * @param status
     */
    public void initQuxiaoDingdan(String number, int status) {
        Map<String, String> map = new TreeMap<>();
        map.put("number", number + "");
        map.put("status", status + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartStatuskey(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartStatuskey_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(CartStatuskey_Info info) {
                        if (info.getCode() == 1) {
                            finish();

                        }
                    }
                });
    }
}
